package com.whz.mlc.provider;

import com.github.benmanes.caffeine.cache.CacheLoader;
import lombok.Data;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.util.Assert;

import java.util.function.Function;

/**
 * @author whz
 */
@Data
public class SimpleMlcCallBack implements MlcCacheDefinition {

    private String cacheName = "mlc-default-cache";

    private Function<Object, Object> function;

    private MlcCacheProperty mlcCacheProperty = new MlcCacheProperty();

    @Override
    public String cacheName() {
        return cacheName;
    }

    @Override
    public CacheLoader<Object, Object> cacheLoader() {
        Assert.notNull(function, "缓存最终未命中时,需要提供回源查询接口.");
        return new CacheLoader<Object, Object>() {
            @Override
            public @Nullable Object load(@NonNull Object key) throws Exception {
                return function.apply(key);
            }
        };
    }

    @Override
    public MlcCacheProperty mlcCacheConfig() {
        return mlcCacheProperty;
    }
}